//
//  JHExplainDetailViewController.m
//  JuniRengLish_iOS
//
//  Created by Maiyou on 2019/5/24.
//  Copyright © 2019 revogi. All rights reserved.
//

#import "JHExplainDetailViewController.h"

@interface JHExplainDetailViewController ()

@property (weak, nonatomic) IBOutlet UILabel *showWord;
@property (weak, nonatomic) IBOutlet UILabel *showBritish;
@property (weak, nonatomic) IBOutlet UILabel *showAmerican;
@property (weak, nonatomic) IBOutlet UILabel *basicExplain;
@property (weak, nonatomic) IBOutlet UILabel *referenceLabel;
@property (weak, nonatomic) IBOutlet UILabel *dicExplanation;
@property (weak, nonatomic) IBOutlet UIButton *explainButton1;
@property (weak, nonatomic) IBOutlet UIButton *explainButton2;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIView *referenceView;
@property (weak, nonatomic) IBOutlet UIView *dicView;
@property (weak, nonatomic) IBOutlet UIView *wordsView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *wordsView_height;

@property (nonatomic, strong) FSAudioStream * audioStream;

@end

@implementation JHExplainDetailViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationItem.title = @"详细解读";
    self.view.backgroundColor = [UIColor whiteColor];
    self.scrollView.hidden = YES;
    
    [self getExplainDetail];
}

- (void)getExplainDetail
{
    NSString * urlStr = [NSString stringWithFormat:@"%@%@", BaseUrl, WordExplainDetail];
    [DJHttpTool postWithURL:urlStr params:@{@"word":self.explainWord,  @"sign":@"1ab075e3659ebef085b2"} success:^(id json) {
        if ([json[@"success"] boolValue])
        {
            self.scrollView.hidden = NO;
            [self parmasData:json[@"data"]];
        }
        else
        {
            if (self.wordDic)
            {
                self.scrollView.hidden = NO;
                [self noDataShowInfo];
            }
        }
    } failure:^(NSError *error) {

    }];
}
#pragma mark - 无数据显示前面的数据
- (void)noDataShowInfo
{
    if (self.type == 1)
    {
        self.showWord.text = self.wordDic[@"word"];
        
        if ([self.wordDic[@"status"] integerValue] == 0)
        {
            NSString * explain = @"";
            NSArray * array = self.wordDic[@"word_mean"];
            for (int i = 0; i < [array count]; i ++)
            {
                [explain isEqualToString:@""] ? explain = array[i] : (explain = [NSString stringWithFormat:@"%@\n%@", explain, array[i]]);
            }
            self.basicExplain.text  = explain;
            
            self.showBritish.text = [NSString stringWithFormat:@"英[%@]", self.wordDic[@"ph_am"]];
            
            self.showAmerican.text = [NSString stringWithFormat:@"美[%@]", self.wordDic[@"ph_en"]];
            
            self.wordsView.hidden = YES;
        }
        else if ([self.wordDic[@"status"] integerValue] == 1)
        {
            self.basicExplain.text  = self.wordDic[@"out"];
            
            self.showBritish.text = [NSString stringWithFormat:@"英[%@]", @""];
            
            self.showAmerican.text = [NSString stringWithFormat:@"美[%@]", @""];
            
            self.wordsView.hidden = YES;
        }
        
        self.referenceLabel.text = @"";
        self.referenceView.hidden = YES;
        self.dicExplanation.text = @"";
        self.dicView.hidden = YES;
    }
    else if (self.type == 2)
    {
        self.showWord.text = self.wordDic[@"rq"];
        
        self.showBritish.text = [NSString stringWithFormat:@"英[%@]", self.wordDic[@"uksm"]];
        
        self.showAmerican.text = [NSString stringWithFormat:@"美[%@]", self.wordDic[@"ussm"]];
        
        NSString * explain = @"";
        NSArray * array = self.wordDic[@"basic"];
        for (int i = 0; i < [array count]; i ++)
        {
            [explain isEqualToString:@""] ? explain = array[i] : (explain = [NSString stringWithFormat:@"%@\n%@", explain, array[i]]);
        }
        self.basicExplain.text = explain;
        
        [self addUnderLine:self.wordDic[@"rec"]];
        
        self.referenceLabel.text = @"";
        self.referenceView.hidden = YES;
        self.dicExplanation.text = @"";
        self.dicView.hidden = YES;
    }
}

// 下划线
- (void)addUnderLine:(NSArray *)recArray
{
    NSDictionary *attribtDic = @{NSUnderlineStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
    if (recArray.count > 1)
    {
        NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:recArray[0] attributes:attribtDic];
        [attribtStr addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor]  range:NSMakeRange(0,[recArray[0] length])];
        [self.explainButton1 setAttributedTitle:attribtStr forState:0];
        
        NSMutableAttributedString *attribtStr1 = [[NSMutableAttributedString alloc]initWithString:recArray[1] attributes:attribtDic];
        [attribtStr1 addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor]  range:NSMakeRange(0,[recArray[1] length])];
        [self.explainButton2 setAttributedTitle:attribtStr1 forState:0];
    }
    else if (recArray.count > 0)
    {
        NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:recArray[0] attributes:attribtDic];
        [attribtStr addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor]  range:NSMakeRange(0,[recArray[0] length])];
        [self.explainButton1 setAttributedTitle:attribtStr forState:0];
        self.explainButton2.hidden = YES;
    }
    else
    {
        self.wordsView.hidden = YES;
        self.wordsView_height.constant = 0;
    }
}

- (void)parmasData:(NSDictionary *)dic
{
    self.showWord.text = dic[@"name"];
    
    self.showBritish.text = [NSString stringWithFormat:@"英[%@]", dic[@"pronunciations"][@"uk"]];
    
    self.showAmerican.text = [NSString stringWithFormat:@"美[%@]", dic[@"pronunciations"][@"us"]];
    
    NSArray * chArray = dic[@"chineses"];
    NSString * str = @"";
    for (NSDictionary * dic in chArray)
    {
        NSString * content = [NSString stringWithFormat:@"%@%@", dic[@"type"], dic[@"value"]];
        if ([str isEqualToString:@""])
        {
            str = content;
        }
        else
        {
            str = [NSString stringWithFormat:@"%@\n%@", str, content];
        }
    }
    self.basicExplain.text = str;
    
    //判断相关词组
    if (self.wordDic)
    {
        [self addUnderLine:self.wordDic[@"rec"]];
    }
    else
    {
        self.wordsView.hidden = YES;
        self.wordsView_height.constant = 0;
    }
    
    NSString * example = @"";
    if (dic[@"example"])
    {
        NSArray * exampleArray = dic[@"example"];
        for (NSDictionary * dic1 in exampleArray)
        {
            NSString * content = [NSString stringWithFormat:@"%@\n%@", dic1[@"en_example"], dic1[@"ch_example"]];
            if ([example isEqualToString:@""])
            {
                example = [NSString stringWithFormat:@"例句：\n%@", content];
            }
            else
            {
                example = [NSString stringWithFormat:@"%@\n%@", str, content];
            }
        }
        self.referenceLabel.text = example;
    }
    else
    {
        self.referenceLabel.text = @"";
        self.referenceView.hidden = YES;
    }
    
    if (dic[@"means"])
    {
        self.dicExplanation.text = [dic[@"means"] stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@""];
    }
    else
    {
        self.dicExplanation.text = @"";
        self.dicView.hidden = YES;
    }
}

- (FSAudioStream *)audioStream
{
    if (!_audioStream)
    {
        //创建FSAudioStream对象
        _audioStream = [[FSAudioStream alloc]init];
        _audioStream.onFailure = ^(FSAudioStreamError error,NSString *description){
            NSLog(@"播放过程中发生错误，错误信息：%@",description);
        };
        _audioStream.onCompletion = ^(){
            NSLog(@"播放完成!");
        };
        _audioStream.onStateChange = ^(FSAudioStreamState state) {
            
        };
        [_audioStream setVolume:1];//设置声音
    }
    return _audioStream;
}

#pragma mark - 播放语音
- (IBAction)voiceButtonClick:(id)sender
{
    UIButton * button = sender;
    switch (button.tag) {
        case 20:
            [self deptNameInputShouldChinese] ?
            [self playWord:self.basicExplain.text Lan:@"uk"] :
            [self playWord:self.showWord.text Lan:@"uk"];
            break;
        case 30:
            [self deptNameInputShouldChinese] ?
            [self playWord:self.basicExplain.text Lan:@"en"] :
            [self playWord:self.showWord.text Lan:@"en"];
            break;
            
        default:
            break;
    }
}

- (void)playWord:(NSString *)word Lan:(NSString *)lan
{
    word = [word stringByAddingPercentEncodingWithAllowedCharacters:  [NSCharacterSet URLUserAllowedCharacterSet]];
    NSString * urlStr = [NSString stringWithFormat:@"https://fanyi.baidu.com/gettts?lan=%@&text=%@&spd=2&source=web", lan, word];
    self.audioStream.url = [NSURL URLWithString:urlStr];
    [self.audioStream play];
}
#pragma mark - 是否为中文
- (BOOL)deptNameInputShouldChinese
{
    NSString *regex = @"[\u4e00-\u9fa5]+";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    if ([pred evaluateWithObject:self.showWord.text]) {
        return YES;
    }
    return NO;
}

- (IBAction)relatedPhrasesClick:(id)sender
{
    UIButton * button = sender;
    JHExplainDetailViewController * explain = [JHExplainDetailViewController new];
    explain.explainWord = button.titleLabel.text;
    explain.type = self.type;
    explain.wordDic = self.wordDic;
    [self.navigationController pushViewController:explain animated:YES];
}

@end
